import { forwardRef, Inject, Injectable } from '@nestjs/common';
import { UpdateMenuDto } from './dto/update-menu.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Menu } from './entities/menu.entity';
import { In, TreeRepository } from 'typeorm';
import { RolesService } from '../roles/roles.service';
@Injectable()
export class MenuService {
  constructor(
    @InjectRepository(Menu)
    private readonly menuRepository: TreeRepository<Menu>,

    @Inject(forwardRef(() => RolesService))
    private rolesService: RolesService,
  ) {}
  async findAll() {
    return this.menuRepository.findTrees();
  }
  async create(body) {
    console.log('createMenuDto', body);
    const menu = await this.menuRepository.create(body);
    if (body.parent) {
      // @ts-ignore
      menu.parent = await this.findOne(body.parent);
    }
    return this.menuRepository.save(menu);
  }

  async findOne(id: number) {
    return await this.menuRepository.findOne({
      relations: { roles: true },
      where: { id },
    });
  }

  findById(ids) {
    return this.menuRepository.findBy({ id: In(ids) });
  }
  async update(id: number, updateMenuDto) {
    const menuTemp = await this.findOne(id);
    if (updateMenuDto.parent) {
      menuTemp.parent = await this.findOne(updateMenuDto.parent);
    }
    return this.menuRepository.save(menuTemp);
  }

  async remove(ids: string) {
    ids.split(',').forEach((id) => this.menuRepository.delete(id));
    return true;
  }
}
